package com.wnnight.wys.web.config;

import com.alibaba.excel.util.StringUtils;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.wnnight.wys.entity.PageBean;
import com.wnnight.wys.entity.config.PropertyStaff;
import com.wnnight.wys.entity.repairs.RepairsPlace;
import com.wnnight.wys.groupInterface.AddGroup;
import com.wnnight.wys.groupInterface.AlterGroup;
import com.wnnight.wys.mapper.config.PropertyStaffMapper;
import com.wnnight.wys.mapper.repairs.RepairsPlaceMapper;
import com.wnnight.wys.security.JwtUtils;
import com.wnnight.wys.service.config.PropertyStaffService;
import com.wnnight.wys.vo.PsdVo;
import com.wnnight.wys.vo.ResultVo;
import com.wnnight.wys.vo.config.PropertyStaffVo;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import javax.sql.rowset.serial.SerialBlob;
import javax.validation.groups.Default;
import java.sql.Blob;
import java.util.List;

/**
 * @ClassName: PropertyStaffController
 * @Description: //TODO
 * @author: LZJ
 * @date: 2022/8/29-23:20
 * @version: v1.0
 */
@RestController
@RequestMapping("/api/v1/config/propertyStaff")
@Slf4j
public class PropertyStaffController {

    private int id;
    @Resource
    private PropertyStaffMapper propertyStaffMapper;

    @Resource
    private PropertyStaffService propertyStaffService;

    @Resource
    private RepairsPlaceMapper repairsPlaceMapper;

    @Value("${wys.propertyStaffPhoto}")//从配置文件里读取信息
    private String propertyStaffPhoto;//员工头像上传的位置

    @PostMapping("/list")
    @PreAuthorize("hasAuthority('config:propertyStaff:list')")
    public ResultVo<PropertyStaff> list(@RequestBody @Validated({AddGroup.class, Default.class}) PropertyStaffVo propertyStaffVo) {
        PageBean<List<PropertyStaff>> pageBean = new PageBean<>();
        QueryWrapper<PropertyStaff> queryWrapper = new QueryWrapper<>();
        if (StringUtils.isNotBlank(propertyStaffVo.getPropertyStaff().getName())) {
            queryWrapper.eq("wps.name", propertyStaffVo.getPropertyStaff().getName());
        }
        if (StringUtils.isNotBlank(propertyStaffVo.getPropertyStaff().getAccount())) {
            queryWrapper.eq("wps.account", propertyStaffVo.getPropertyStaff().getAccount());
        }
        if (StringUtils.isNotBlank(propertyStaffVo.getPropertyStaff().getPhone())) {
            queryWrapper.eq("wps.phone", propertyStaffVo.getPropertyStaff().getPhone());
        }
        if (StringUtils.isNotBlank(propertyStaffVo.getPropertyStaff().getUpdateTime())) {
            queryWrapper.eq("wps.update_time", propertyStaffVo.getPropertyStaff().getUpdateTime());
        }
        if (propertyStaffVo.getPropertyStaff().getRole() != null && propertyStaffVo.getPropertyStaff().getRole().toString().trim().equals("")) {
            queryWrapper.eq("wr.id", propertyStaffVo.getPropertyStaff().getRole().getId());
        }
        if (propertyStaffVo.getPropertyStaff().getImg() != null && propertyStaffVo.getPropertyStaff().getImg().toString().trim().equals("")) {
            queryWrapper.eq("wps.img", propertyStaffVo.getPropertyStaff().getImg());
        }
        IPage<PropertyStaff> propertyStaffs = propertyStaffService.getAll(new Page<>(propertyStaffVo.getPage(), propertyStaffVo.getPageSize()), queryWrapper);
        pageBean.setData(propertyStaffs.getRecords());
        pageBean.setCurrPage(propertyStaffVo.getPage());
        pageBean.setPageSize(propertyStaffVo.getPageSize());
        pageBean.setTotalNum((int) propertyStaffs.getTotal());
        pageBean.setTotalPages((int) propertyStaffs.getPages());
        for (PropertyStaff staff : propertyStaffs.getRecords()) {
            List<RepairsPlace> repairsPlaces = repairsPlaceMapper.selectByStaffId(staff.getId());
            for (RepairsPlace repairsPlace : repairsPlaces) {
                if (staff.getArea() == null) {
                    staff.setArea(repairsPlace.getName());
                } else {
                    String area1 = staff.getArea();
                    String area2 = repairsPlace.getName();
                    staff.setArea(area1 + "、" + area2);
                }
            }
        }
        return new ResultVo(propertyStaffs);
    }

    @PostMapping("/update")
    public ResultVo<String> update(@RequestBody @Validated(AlterGroup.class) PropertyStaffVo propertyStaffVo) {
        propertyStaffService.update(propertyStaffVo.getPropertyStaff(), propertyStaffVo.getPalceIds());
        return ResultVo.SUCCESS;
    }

    @PostMapping("/delete/{id}")
    @PreAuthorize("hasAuthority('config:propertyStaff:delete')")
    public ResultVo<String> delete(@PathVariable int id) {
        propertyStaffService.removeById(id);
        return ResultVo.SUCCESS;
    }

    @PostMapping("/upload/propertyStaffPhoto")
    @PreAuthorize("hasAuthority('config:propertyStaff:upload:propertyStaffPhoto')")
    public ResultVo<String> uploadPropertyStaffPhoto(MultipartFile file) {
        log.debug("file:{}", file);
        log.debug("propertyStaffPhoto:{}", propertyStaffPhoto);
        String img = null;
        try {
            Blob blob = new SerialBlob(file.getBytes());
            byte[] blobBytes = blob.getBytes(1, (int) blob.length());
            PropertyStaff propertyStaff = new PropertyStaff();
            propertyStaff.setId(id);
            propertyStaff.setImg(blobBytes);
            propertyStaffMapper.update(propertyStaff);
            img = file.getOriginalFilename();
//            file.transferTo(new File(propertyStaffPhoto + "/" + file.getOriginalFilename()));//图片传过来存放地址
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
        return new ResultVo(img);
    }

    @PostMapping("/add")
    @PreAuthorize("hasAuthority('config:propertyStaff:add')")
    public ResultVo<String> add(@RequestBody @Validated(AddGroup.class) PropertyStaffVo propertyStaffVo) {
        propertyStaffService.add(propertyStaffVo.getPropertyStaff(), propertyStaffVo.getPalceIds());
        id = propertyStaffVo.getPropertyStaff().getId();
        return ResultVo.SUCCESS;
    }

    @PostMapping("/isSame")
    public ResultVo<String> getPsd(@RequestBody PsdVo psdVo) {
        int id = (int) JwtUtils.getInfo(psdVo.getJwt(), "id");
        PropertyStaff user = propertyStaffService.getById(id);
        String password = user.getPassword();
        String OldPassword = "";
        PasswordEncoder encoder = new BCryptPasswordEncoder();
        Boolean isSame = false;
        if (psdVo.getPsd() != null) {
            OldPassword = psdVo.getPsd();
            if (encoder.matches(OldPassword, password)) {
                return new ResultVo<>("same");
            }
            ;
        }
        return new ResultVo<>("nosame");
    }

    @PostMapping("/updatePsd")
    public ResultVo<String> update(@RequestBody PsdVo psdVo) {
        System.out.println(psdVo);
        System.out.println(psdVo.getPsd());
        int id = (int) JwtUtils.getInfo(psdVo.getJwt(), "id");
        String password = "";
        if (psdVo.getPsd() != null) {
            password = psdVo.getPsd();
        }
        propertyStaffService.updatePsd(id, password);
        return ResultVo.SUCCESS;
    }

    @PostMapping("/getById")

    public ResultVo<PropertyStaff> getById(@RequestBody String jwt) {
        int id = (int) JwtUtils.getInfo(jwt, "id");
        PropertyStaff user = propertyStaffService.getById(id);

        return new ResultVo<>(user);
    }

    @RequestMapping("getPhoto")
    public byte[] getPhoto() {
        final byte[][] img = new byte[1][1];
        List<PropertyStaff> propertyStaffs = propertyStaffService.getImg();
        propertyStaffs.forEach(propertyStaff ->
                img[0] = propertyStaff.getImg()
        );
        return img[0];
    }
}
